package com.wjd.wshow.service.impl;

import com.wjd.wshow.config.ContextHolder;
import com.wjd.wshow.entity.BaseEntity;
import com.wjd.wshow.repository.BaseRepository;
import com.wjd.wshow.service.BaseService;

import javax.transaction.Transactional;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Optional;

public class BaseServiceImpl<T extends BaseEntity, ID> implements BaseService<T, ID> {

    @Transactional
    @Override
    public T create(T entity) {
        T result;
        BaseRepository<T, ID> repository = getRepository();
        if (repository == null) {
            return null;
        }
        result = repository.save(entity);
        return result;
    }

    @Override
    public T get(ID id) {
        T result;
        BaseRepository<T, ID> repository = getRepository();
        if (repository == null) {
            return null;
        }
        Optional<T> optional = repository.findById(id);
        if (!optional.isPresent()) {
            return null;
        }
        result = optional.get();
        return result;
    }

    @Transactional
    @Override
    public T update(T entity) {
        T result;
        BaseRepository<T, ID> repository = getRepository();
        if (repository == null) {
            return null;
        }
        result = repository.save(entity);
        return result;
    }

    @Transactional
    @Override
    public void deleteById(ID id) {
        BaseRepository<T, ID> repository = getRepository();
        if (repository == null) {
            return;
        }
        repository.deleteById(id);
    }

    @Transactional
    @Override
    public void delete(T entity) {
        BaseRepository<T, ID> repository = getRepository();
        if (repository == null) {
            return;
        }
        repository.delete(entity);
    }

    /**
     * 获取实体访问对象
     * @return 实体访问对象
     */
    @SuppressWarnings("unchecked")
    protected BaseRepository<T, ID> getRepository() {
        BaseRepository<T, ID> repository;
        Class<T> entityClass = getParameterizedEntityType();
        String entityName = entityClass.getName();
        String repositoryName = entityName + "Repository";
        repository = (BaseRepository<T, ID>) ContextHolder.getInstance().getBean(repositoryName);
        return repository;
    }

    /**
     * 获取实体泛型参数的实际类型
     * @return 实体的实际类型
     */
    @SuppressWarnings("unchecked")
    protected Class<T> getParameterizedEntityType() {
        Type type = getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) type;
            System.out.println(parameterizedType.getActualTypeArguments()[0]);
            return (Class<T>) parameterizedType.getActualTypeArguments()[0];
        }
        throw new RuntimeException();
    }
}
